// 封装微信小程序的请求函数
// 这个是非云托管
function wxRequest(url, method, data) {
	// 获得请求头
	return new Promise((resolve, reject) => {
		let header = {
			'Content-type': 'application/json',
		}
		let userInfo = wx.getStorageSync("userInfo")
		let token = wx.getStorageSync('token')
		if (userInfo) {
			header = {
				'token': `${token}`,

				'Content-type': 'application/json',
			}
		}
		wx.request({
			header: header,
			url: url,
			method: method || 'GET',
			data: data,
			success: (res) => {
				if (res.statusCode === 200) {
					// 请求成功，将结果传递给 resolve 函数
					resolve(res.data);
				} else if (res.statusCode === 401) {
					// 如果没登录 先转跳到登录
					wx.showModal({
						title: '请先登录',
						showCancel: false,
						complete: (res) => {
							if (res.confirm) {
								wx.switchTab({
									url: "/pages/login/login"
								})
							}
							resolve(false)
						}
					})

				} else {
					// 请求失败，将错误信息传递给 reject 函数
					reject(new Error(`Request failed with status code ${res.statusCode}`));
				}
			},
			fail: (error) => {
				// 请求失败，将错误信息传递给 reject 函数
				reject(error);
			},
		});
	});
}




// 这个是云托管
function wxRequest1(url, method, data) {
	return new Promise((resolve, reject) => {
		wx.cloud.callContainer({
			"config": {
				"env": "prod-5gxutld389e76c89"
			},
			method: method,
			path: url,
			"header": {
				"X-WX-SERVICE": "springboot-5uxp"
			},
			data: data,
			success: (res) => {

				if (res.statusCode === 200) {
					// 请求成功，将结果传递给 resolve 函数
					resolve(res.data);
				} else {
					// 请求失败，将错误信息传递给 reject 函数
					reject(new Error(`Request failed with status code ${res.statusCode}`));
				}
			},
			fail: (error) => {
				// 请求失败，将错误信息传递给 reject 函数
				reject(error);
			},
		});
	});
}

// 云托管测试版本
function wxRequest2(url, method, data) {
	return new Promise((resolve, reject) => {
		wx.cloud.callContainer({
			"config": {
				"env": "prod-5gxutld389e76c89"
			},
			"path": "/",
			"header": {
				"X-WX-SERVICE": "springboot-5uxp"
			},
			"method": "GET",
			"data": {
				"action": "inc"
			},
			success: res => {
				resolve(res)
				console.log(res)
			},
			fail: err => {
				reject(err)
				console.log(err)
			}
		})
	})
}
module.exports = {
	wxRequest: wxRequest,
};